<?php

#error_reporting(E_ALL);
require_once($_SERVER['DOCUMENT_ROOT'].'../system/config.php');
require_once($INCLUDE_DIR.'pel/PelJpeg.php');

require_once $INCLUDE_DIR.'cametrics.helper.php';

function convertDecimalToDMS($degree) {
  if ($degree > 180 || $degree < -180)
    return null;

  $degree = abs($degree);            // make sure number is positive
                                     // (no distinction here for N/S
                                     // or W/E).

  $seconds = $degree * 3600;         // Total number of seconds.

  $degrees = floor($degree);         // Number of whole degrees.
  $seconds -= $degrees * 3600;       // Subtract the number of seconds
                                     // taken by the degrees.

  $minutes = floor($seconds / 60);   // Number of whole minutes.
  $seconds -= $minutes * 60;         // Subtract the number of seconds
                                     // taken by the minutes.

  $seconds = round($seconds*100, 0); // Round seconds with a 1/100th
                                     // second precision.

  return array(array($degrees, 1), array($minutes, 1), array($seconds, 100));
}

function addGpsInfo($input, $output, $description, $comment, $model,
                    $longitude, $latitude, $altitude, $date_time) {
  /* Load the given image into a PelJpeg object */
  $jpeg = new PelJpeg($input);

  /* Create and add empty Exif data to the image (this throws away any
   * old Exif data in the image). */
  $exif = new PelExif();
  $jpeg->setExif($exif);

  /* Create and add TIFF data to the Exif data (Exif data is actually
   * stored in a TIFF format). */
  $tiff = new PelTiff();
  $exif->setTiff($tiff);

  /* Create first Image File Directory and associate it with the TIFF
   * data. */
  $ifd0 = new PelIfd(PelIfd::IFD0);
  $tiff->setIfd($ifd0);

  /* Create a sub-IFD for holding GPS information. GPS data must be
   * below the first IFD. */
  $gps_ifd = new PelIfd(PelIfd::GPS);
  $ifd0->addSubIfd($gps_ifd);

  /* The USER_COMMENT tag must be put in a Exif sub-IFD under the
   * first IFD. */
  $exif_ifd = new PelIfd(PelIfd::EXIF);
  $exif_ifd->addEntry(new PelEntryUserComment($comment));
  $ifd0->addSubIfd($exif_ifd);

  $inter_ifd = new PelIfd(PelIfd::INTEROPERABILITY);
  $ifd0->addSubIfd($inter_ifd);

  $ifd0->addEntry(new PelEntryAscii(PelTag::MODEL, $model));
  $ifd0->addEntry(new PelEntryAscii(PelTag::DATE_TIME, $date_time));
  $ifd0->addEntry(new PelEntryAscii(PelTag::IMAGE_DESCRIPTION, $description));

  $gps_ifd->addEntry(new PelEntryByte(PelTag::GPS_VERSION_ID, 2, 2, 0, 0));

  /* Use the convertDecimalToDMS function to convert the latitude from
   * something like 12.34� to 12� 20' 42" */
  list($hours, $minutes, $seconds) = convertDecimalToDMS($latitude);

  /* We interpret a negative latitude as being south. */
  $latitude_ref = ($latitude < 0) ? 'S' : 'N';

  $gps_ifd->addEntry(new PelEntryAscii(PelTag::GPS_LATITUDE_REF,
                                       $latitude_ref));
  $gps_ifd->addEntry(new PelEntryRational(PelTag::GPS_LATITUDE,
                                          $hours, $minutes, $seconds));

  /* The longitude works like the latitude. */
  list($hours, $minutes, $seconds) = convertDecimalToDMS($longitude);
  $longitude_ref = ($longitude < 0) ? 'W' : 'E';

  $gps_ifd->addEntry(new PelEntryAscii(PelTag::GPS_LONGITUDE_REF,
                                       $longitude_ref));
  $gps_ifd->addEntry(new PelEntryRational(PelTag::GPS_LONGITUDE,
                                          $hours, $minutes, $seconds));

  /* Add the altitude. The absolute value is stored here, the sign is
   * stored in the GPS_ALTITUDE_REF tag below. */
  $gps_ifd->addEntry(new PelEntryRational(PelTag::GPS_ALTITUDE,
                                          array(abs($altitude), 1)));
  /* The reference is set to 1 (true) if the altitude is below sea
   * level, or 0 (false) otherwise. */
  $gps_ifd->addEntry(new PelEntryByte(PelTag::GPS_ALTITUDE_REF,
                                      (int)($altitude < 0)));

  /* Finally we store the data in the output file. */
  file_put_contents($output, $jpeg->getBytes());
}


// Create new phpFlickr object
//session_start();
require_once($INCLUDE_DIR."phpflickr.helper.php");
$f->auth('write');
$logfile = $BASE_DIR.'../logs/campaignrflickr.log';

echo "Data successfully slogged!\n";
$xml_str = stripslashes($_POST['data_string']);
#file_put_contents('campaignrflickr.log', $xml_str."\r\n", FILE_APPEND);

$xml_str = preg_replace("/field name=\"([^\"]+)\">([^<]+)?<\/field>/", '$1>$2</$1>', $xml_str);
$data = simplexml_load_string($xml_str);

file_put_contents($logfile, print_r($data, true)."\r\n", FILE_APPEND);

// open database
$db = new PDO("sqlite:".$DATABASE);

foreach($data->row as $field)
{
	$image = $field->image;
	$ismedia = $field->ismedia;
	$timestamp = $field->timestamp;
	$location = $field->location;
	$imei = $field->imei;
	$type = $field->type;

	$type = str_replace(" ", "", $type);
        $type = str_replace("[", "", $type);
        $type = str_replace("]", "", $type);
	$type = str_replace(' " ', '', $type);
        $type = str_replace('"', '', $type);   
	$type = str_replace(",", " ", $type);

	$location = str_replace("NaN",'""',$location);
	$location = json_decode($location);

	$latitude = $location->latitude;
	$longitude = $location->longitude;

	$imagefile = tmpfile();
	fwrite($imagefile, $image);

	$imagefilename = tempnam("/tmp", "img");

	$imagehandle = fopen($imagefilename, "w");
	fwrite($imagehandle, base64_decode($image));
	fclose($imagehandle);

	$is_public = 1;
	$is_friend = 1;
	$is_family = 1;

	$tags = $imei." nolabel ".$type;

	$description = "";

	list($day, $other) = split('T', $timestamp);
	$time = substr($other, 0, 8);
	$title = $day;

	$result = $db->query("SELECT username, usergroup FROM user WHERE imei=$imei");
	if (!$result) {
		$username = $imei;
		$groupname = 'group_'.$imei;
	}

	$row = $result->fetch(PDO::FETCH_ASSOC);

	if (!$row || count($row) < 2) {
		$username = $imei;
		$groupname = 'group_'.$imei;
	}
	else {
		$username = $row['username'];
		$groupname = $row['usergroup'];
	}

	$db = null;

	$type = strtolower($type);
	$username = strtolower($username);
	$groupname = strtolower($groupname);

        Cametrics::measure($username.".contributions.type", $type, 'string');
        Cametrics::measure($username.".contributions.time", $day.' '.$time, 'datetime');

        Cametrics::measure($groupname.".contributions", $username, 'string');             
        Cametrics::measure($groupname.".contributions.type", $type, 'string');
        Cametrics::measure($groupname.".contributions.time", $day.' '.$time, 'datetime');
        Cametrics::measure("contributions.group", $groupname, 'string');


        Cametrics::measure("contributions", $username, 'string');             
        Cametrics::measure("contributions.type", $type, 'string');
        Cametrics::measure("contributions.time", $day.' '.$time, 'datetime');


	if(($latitude != "") and ($longitude != "") and ($latitude != "NaN") and ($longitude != "NaN"))
	{
	        #$tags = $tags." "."geo:lat:".$latitude." "."geo:long:".$longitude;

		$imagefilenameexif = $imagefilename."mod";     

		addGpsInfo($imagefilename, $imagefilenameexif, "", "", "", $longitude, $latitude, "", $timestamp);

		$response = $f->sync_upload($imagefilenameexif, $title, "", $tags, 1, 1, 1);
		file_put_contents($logfile, "ImageFilename:".$imagefilename." Tags:".$tags." Location:".$latitude." Longitude: ".$longitude." Response:".$response."\r\n", FILE_APPEND);

	        Cametrics::measure($username.".contributions.location.all", $longitude.",".$latitude, 'location');
	        Cametrics::measure($groupname.".contributions.location.all", $longitude.",".$latitude, 'location');
                Cametrics::measure("contributions.location.all", $longitude.",".$latitude, 'location');

	        Cametrics::measure($username.".contributions.location.".$type, $longitude.",".$latitude, 'location');
	        Cametrics::measure($groupname.".contributions.location.".$type, $longitude.",".$latitude, 'location');
                Cametrics::measure("contributions.location.".$type, $longitude.",".$latitude, 'location');

	        Cametrics::measure("$groupname.contributions.location.$username.$type", $longitude.",".$latitude, 'location');
                Cametrics::measure("contributions.location.$username.$type", $longitude.",".$latitude, 'location');

	        Cametrics::measure("$groupname.contributions.location.$username.all", $longitude.",".$latitude, 'location');
                Cametrics::measure("contributions.location.$username.all", $longitude.",".$latitude, 'location');

		unlink($imagefilename);
		unlink($imagefilenameexif);
	}
	else
	{

		$response = $f->sync_upload($imagefilename, $title, "", $tags, 1, 1, 1);
		file_put_contents($logfile, "ImageFilename:".$imagefilename." Tags:".$tags." Response:".$response."\r\n", FILE_APPEND);

		unlink($imagefilename);       

	}
}

?>
